﻿#include <boost/asio.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <fstream>
#include "json/json.h"
using namespace std;

/**
 * ref http://reverland.org/python/2014/01/29/python/
 * @brief getline read the  response string and return a line of the response
 * @param response
 * @return
 */
string getline(string  & response){

    string line = "";
    int count = 0;
    while(count < response.length ()){
        char c = response[count];
        char cf = response[count + 1];
        if(c == '\r'  && cf == '\n'){
            line += "\r\n";
            break;
        }
        line += c;
        count ++;
    }
    response =  response.substr ( count + 2 , response.length () - count); // change the response , a line lost
    return line;
}


/**
 * ref http://reverland.org/python/2014/01/29/python/
 * @brief getheader read the header of the response
 * @param response
 * @return
 */
string getheader(string  & response){
    string header = "";
    while(1){
        string line = getline (response);
        if (line == string("\r\n"))
            break;
        header += line;
    }
    return header;
}

int main(int arg  ,char * argv[]) {

    /**
     * @brief ip port para set from command
     * para is used in Get /para  request
     */
    string ip = argv[1];
    string port = argv[2];
    string para = argv[3];


    boost::system::error_code ec;
    using namespace boost::asio;
    io_service svc;
    ip::tcp::socket sock(svc);
    sock.connect({ ip::address_v4::from_string(ip), unsigned short (stoi(port)) });

    // send request
    std::string request("GET /"+para+ " HTTP/1.1\r\n\r\n");
    sock.send(buffer(request));

    // read response
    std::string response;

    do {
        char buf[1024];
        size_t bytes_transferred = sock.receive(buffer(buf), {}, ec);
        if (!ec) response.append(buf, buf + bytes_transferred);
    } while (!ec);

    //response look like as follow
/*

    HTTP/1.0 200 OK
    Content-Type: application/json
    Content-Length: 35
    Server: Werkzeug/0.10.1 Python/2.7.3
    Date: Thu, 26 Mar 2015 08:53:25 GMT

    {
        "isRegistration": "unkown"
    }
*/


//    std::cout << response;
//    cout<<"\n-----header----------\n"<<endl;
//    cout<<getheader (response);
//    cout<<"\n-----body----------\n"<<endl;
//    cout<<response;

    getheader (response);

    Json::Reader reader;
    Json::Value value;
    if (reader.parse(response, value))
    {
        std::string out = value["isRegistration"].asString();
        std::cout << out << std::endl;
    }
}
